package main

import (
	"encoding/binary"
	"fmt"
	"log"
	"net"
)

func main() {
	listener, err := net.Listen("tcp", ":2000")
	if err != nil {
		log.Fatalln("服务器启动失败", err)
		return
	}
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("获取客户端失败", err)
			continue
		}
		go process(conn)
	}
}

func process(conn net.Conn) {
	defer conn.Close()
	for {
		pkgLenBytes := make([]byte, 4)
		n, err := conn.Read(pkgLenBytes)
		if err != nil || n != 4 {
			fmt.Println("读取长度数据失败", err)
			return
		}
		pkgLen := binary.BigEndian.Uint32(pkgLenBytes)
		surplusLen := pkgLen - 4
		msg := make([]byte, surplusLen)
		n, err = conn.Read(msg)
		if err != nil || n != int(surplusLen) {
			fmt.Println("读取剩余消息失败", err)
			return
		}
		headerLenBytes := msg[0:2]
		headerLen := binary.BigEndian.Uint32(headerLenBytes)
		surplusHeaderLen := headerLen - 4
		header := msg[0:surplusHeaderLen]
		version := msg[2:4]
		op := msg[4:8]
		sid := msg[8:12]
		extralHeader := msg[12:surplusHeaderLen]
		body := msg[surplusHeaderLen:]
		go handal(header, version, op, sid, extralHeader, body)
	}
}

func handal(header []byte, version []byte, op []byte, sid []byte, extralHeader []byte, body []byte) {
	fmt.Println(string(body))
}
